//
//  DYThemePhotoView.m
//  BaiSi
//
//  Created by mac on 16/10/31.
//  Copyright © 2016年 DeYi. All rights reserved.
//

#import "DYThemePhotoView.h"
#import "DYThemeItem.h"
#import <UIImageView+WebCache.h>
#import <DALabeledCircularProgressView.h>
#import "DYBigPictureViewController.h"

@interface DYThemePhotoView()

@property (weak, nonatomic) IBOutlet UIImageView *gifView;
@property (weak, nonatomic) IBOutlet UIImageView *photoView;
@property (weak, nonatomic) IBOutlet UIButton *seeBigView;

@property (weak, nonatomic) IBOutlet DALabeledCircularProgressView *progressView;

@end

@implementation DYThemePhotoView

//初始化ProgressView
- (void)awakeFromNib {
    _progressView.roundedCorners = 10;
    _progressView.tintColor = [UIColor lightGrayColor];
    _progressView.trackTintColor = [UIColor clearColor];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    DYBigPictureViewController *vc = [[DYBigPictureViewController alloc] init];
    vc.item = self.item;
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:vc animated:YES completion:nil];
    
}

- (void)setItem:(DYThemeItem *)item {
    [super setItem:item];
    _gifView.hidden = !item.is_gif;
    _seeBigView.hidden = !item.is_big;
    //判断是否是大图
    if (item.is_big) {
        _photoView.contentMode = UIViewContentModeTop;
        _photoView.layer.masksToBounds = YES;
    } else {
        _photoView.contentMode = UIViewContentModeScaleToFill;
        _photoView.layer.masksToBounds = NO;
    }
    [_photoView sd_setImageWithURL:[NSURL URLWithString:item.image0] placeholderImage:nil options:SDWebImageRetryFailed  progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        CGFloat progress = 1.0 * receivedSize / expectedSize;
        if (progress < 0) {
            return ;
        }
        _progressView.progress = progress;
        _progressView.progressLabel.text =[NSString stringWithFormat:@"%0.2f%%",progress * 100];

    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
       
        if (error) {
            LHLog(@"error = %@",error);
        }
         //大图
        if (item.is_big) {
            //重新绘图
            CGFloat margin = 10;
            CGFloat bigPictureW = DYScreenW - 2 * margin;
            CGFloat bigPictureH = (bigPictureW / image.size.width) * image.size.height;
            CGSize imageSize = CGSizeMake(bigPictureW, bigPictureH);
            UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
            [image drawInRect:CGRectMake(0, 0, bigPictureW, bigPictureH)];
            image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            _photoView.image = image;
            
            
        }
       
        
    }];
    
}

@end
